import sys
import threading
from   wsgiref   import simple_server
from   selenium  import webdriver
from   amodel    import Amodel
from   myapp     import app

exec(open(app.root_path + '/constants/tests_constants.py').read())


def before_all(context):
  print("initializing behave tests")
  context.server = context.thread = context.browser = None

  try:
    context.server = simple_server.make_server('' , 5000 , app)
    context.thread = threading.Thread(target = context.server.serve_forever)
    context.thread.start()
    context.browser = webdriver.Firefox()
  except:
    print("behave init failed")
    dump_exception('before_all()')
    after_all(context)


def after_all(context):
  print("cleanup behave tests")
  if context.server  != None: context.server.shutdown()
  if context.thread  != None: context.thread.join()
  if context.browser != None: context.browser.quit()


def before_feature(context , feature):
  try:
    context.amodel = Amodel()
  except:
    dump_exception('before_feature()')


def dump_exception(src):
  print( "EXCEPTION in %s: %s %s" % (src , sys.exc_info()[0] , sys.exc_info()[1]))
